using UnityEngine;

public class Character : MonoBehaviour
{
    #region  Direction Info    
    public int facingDir { get; private set; } = 1;
    protected bool facingRight = true;

    public System.Action onFlipped;

    #endregion

    #region Collision Check Info

    [SerializeField] protected Transform groundCheckPos;
    [SerializeField] protected float groundCheckRadius;
    [SerializeField] protected LayerMask groundLayer;

    [SerializeField] protected Vector2 wallCheckOffset;
    [SerializeField] protected float wallCheckRadius;
    [SerializeField] protected LayerMask wallLayer;

    [SerializeField] public Transform attackCheckPos;
    [SerializeField] public float attackCheckRadius;
    #endregion

    #region SkillInfo

    public SkillDataBase skillDataBase;

    #endregion

    #region Compents

    public CharacterStats stats;
    public Animator anim { get; private set; }
    public Rigidbody2D rb { get; private set; }

    #endregion

    protected virtual void Awake()
    {

    }

    protected virtual void Start()
    {
        anim = GetComponentInChildren<Animator>();
        rb = GetComponent<Rigidbody2D>();
        stats = GetComponent<CharacterStats>();
    }

    protected virtual void Update()
    {

    }

    #region Collision Function

    public bool IsGroundDetected() => Physics2D.OverlapCircle((Vector2)groundCheckPos.position, groundCheckRadius, groundLayer);
    public bool IsWallDetected() => Physics2D.OverlapCircle((Vector2)transform.position + wallCheckOffset, wallCheckRadius, wallLayer);

    private void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireSphere((Vector2)groundCheckPos.position, groundCheckRadius);
        Gizmos.DrawWireSphere((Vector2)transform.position + wallCheckOffset, wallCheckRadius);
        Gizmos.DrawWireSphere((Vector2)attackCheckPos.position, attackCheckRadius);
    }

    #endregion

    #region Direction Controller Function
    private void Flip()
    {
        facingDir = facingDir * -1;
        facingRight = !facingRight;
        transform.Rotate(0, 180, 0);

        if (onFlipped != null)
            onFlipped();
    }

    public void FlipController(float _x)
    {
        if (_x > 0 && !facingRight)
            Flip();
        else if (_x < 0 && facingRight)
            Flip();
    }
    #endregion

    #region Velocity Function   
    public virtual void SetZeroVelocity()
    {
        //if (isKnocked)
        //return;

        rb.velocity = Vector2.zero;
    }

    public virtual void SetVelocity(float _xVelocity, float _yVelocity)
    {
        //if (isKnocked)
        //return;

        rb.velocity = new Vector2(_xVelocity, _yVelocity);
        FlipController(_xVelocity);
    }
    #endregion
}
